package com.spider.controller;

import com.spider.entites.User;
import com.spider.service.UserService;
import com.spider.vo.PageVo;
import com.spider.vo.ResultVo;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author panglin
 * @date 2020/11/19 13:09
 */
@RestController
@RequestMapping("api")
public class UserController {

    @Resource
    private UserService userService;

    @GetMapping("users")
    public ResultVo getUsers(@RequestParam("info") String info, @RequestParam("pageNum") Integer pageNum, @RequestParam("pageSize") Integer pageSize) {
        List<User> users = this.userService.getUsers(info, pageNum, pageSize);
        if (CollectionUtils.isEmpty(users)) {
            return ResultVo.builder(404, "数据为空");
        }
        PageVo pageVo = new PageVo(users, this.userService.getTotal(info));
        return ResultVo.builder(200, "查询成功", pageVo);
    }

    @PostMapping("addUser")
    public ResultVo addUser(@RequestBody User user) {
        Integer flag = this.userService.addUser(user);
        if (flag == 1) {
            return ResultVo.builder(200, "添加成功");
        }
        return ResultVo.builder(500, "添加失败");
    }

    @DeleteMapping("delete")
    public ResultVo delete(@RequestParam("name") String username) {
        Integer flag = this.userService.deleteByName(username);
        if (flag == 1) {
            return ResultVo.builder(200, "删除成功");
        }
        return ResultVo.builder(500, "删除失败");
    }

    @GetMapping("getUserById")
    public ResultVo getUserById(@RequestParam("id") Integer id) {
        User user = this.userService.getUserById(id);
        if (user == null) {
            return ResultVo.builder(404, "不存在该用户");
        }
        return ResultVo.builder(200, "查询成功", user);
    }

    @PutMapping("updateUser")
    public ResultVo updateUserById(@RequestBody User user) {
        Integer flag = this.userService.updateUserById(user);
        if (flag == 1) {
            return ResultVo.builder(200, "更新成功");
        }
        return ResultVo.builder(500, "更新失败");
    }
}
